package dept

import (
	"context"
	"go-zero-project/services/user/rpc/internal/mapper"
	"go-zero-project/services/user/rpc/internal/mapper/bo"
	"go-zero-project/services/user/rpc/internal/svc"
	"go-zero-project/services/user/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type PageListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeptPageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PageListLogic {
	return &PageListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PageListLogic) DeptPageList(in *pb.DeptPageListReq) (*pb.DeptPageListResp, error) {
	// 1.查询总共条数
	deptBO := bo.SysDeptBO{NameLike: in.DeptName, ParentId: 0, HasDelFlag: true, DelFlag: 0}
	deptMapper := mapper.NewDeptMapper()
	selectCount, err := deptMapper.SelectCount(l.svcCtx.DBEngin, deptBO)
	if err != nil {
		return nil, err
	}
	// 2.分页查询部门信息
	pageNum := in.PageNum
	resp := new(pb.DeptPageListResp)
	resp.TotalPage = int32(selectCount)
	resp.CurrentPage = pageNum
	if selectCount < 1 {
		return resp, nil
	}
	pageSize := in.PageSize
	startPageIndex := 0
	if pageNum > 1 {
		startPageIndex = int((pageNum - 1) * pageSize)
	}
	deptBO.StartIndex = startPageIndex
	deptBO.PageSize = int(pageSize)
	deptBO.HasDelFlag = true
	deptBO.DelFlag = 0
	deptArr, err := deptMapper.SelectList(l.svcCtx.DBEngin, deptBO)
	if err != nil {
		return nil, err
	}
	// 3.查询所有子菜单个数
	var deptIdArr []int64
	for _, v := range deptArr {
		deptIdArr = append(deptIdArr, v.DeptId)
	}
	subCountArr, err := deptMapper.SelectSubCount(l.svcCtx.DBEngin, deptIdArr)
	if err != nil {
		return nil, err
	}
	// 4.返回参数处理
	subCountMap := make(map[int64]int32)
	if len(subCountArr) > 0 {
		for _, v := range subCountArr {
			subCountMap[v.DeptId] = v.Count
		}
	}
	var dataList []*pb.DeptInfoResp
	for _, v := range deptArr {
		subCount := subCountMap[v.DeptId]
		infoResp := &pb.DeptInfoResp{DeptId: v.DeptId, Name: v.Name, ParentId: v.ParentId,
			OrderNum: int32(v.OrderNum), SubNodeNum: subCount,
		}
		dataList = append(dataList, infoResp)
	}
	resp.Data = dataList
	return resp, nil
}
